import time
from random import random, randint

from flask import request
from flask import Flask
import pymysql
from flask import jsonify
from flask_cors import *

import common
from auth.auths import Auth
from utils.token import jwtEncoding

app = Flask(__name__)
CORS(app, supports_credentials=True)


@app.route('/test',methods=['GET'])
def gettest():
    t=randint(1,10)
    print(t)
    time.sleep(t)
    data = {}
    data['t'] = t
    data["code"] = "200"
    return jsonify(data)

@app.route('/getimage', methods=['POST'])
def getimage():
    data = request.get_json()
    limit = int(data['limit'])
    page = (int(data['page']) - 1) * limit
    conn = pymysql.connect(host="localhost", user="root", password="DxPass@word!@#", database="autolabel",
                           charset="utf8", cursorclass=pymysql.cursors.DictCursor)
    # 得到一个可以执行SQL语句的光标对象
    cursor = conn.cursor()
    cursorcount = conn.cursor()
    # 定义要执行的SQL语句
    sql = 'select * from autolabel limit %s,%s'
    sqlcount = 'select count(*) from autolabel'
    cursor.execute(sql, [page, limit])
    cursorcount.execute(sqlcount)
    aa = cursor.fetchall()
    cc = cursorcount.fetchall()
    # conn.commit()
    # 关闭光标对象
    cursor.close()
    cursorcount.close()
    # 关闭数据库连接
    conn.close()
    data = {}
    data["code"] = "200"
    data["total"] = cc[0]['count(*)']
    data["list"] = aa
    return jsonify(data)

@app.route('/getauth', methods=['GET'])
def auth():
    # payload  = {
    #     'exp': datetime.datetime.now() + datetime.timedelta(days=1),  # 过期时间
    #     'iat': datetime.datetime.now(),  # 开始时间
    #     'iss': 'lianzong',  # 签名
    #     'data': {  # 内容，一般存放该用户id和开始时间
    #         'a': 1,
    #         'b': 2,
    #     },
    # }
    #
    # s = jwt.encode(payload , 'secret', algorithm='HS256')  # 加密生成字符串
    # print(s)
    # s = jwt.decode(s, 'secret', issuer='lianzong', algorithms=['HS256'])  # 解密，校验签名
    # print(s)
    # print(type(s))

    userInfo = {
        "id": 1,
        "username": "duxing",
    }
    token = jwtEncoding(userInfo)
    return jsonify("{'ok':True,'token':"+token.decode()+"}", "you are sucess")



@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    print(data,'show dattt!!')
    username = data['username']
    password = data['password']
    print(username,'username+++')
    if (not username or not password):
        # return jsonify(common.falseReturn('', '用户名和密码不能为空'))
        return '失败了'
    else:
        return Auth.authenticate(Auth, username, password)
@app.route('/user', methods=['GET'])
def get():
    result = Auth.identify(Auth, request)
    print(result,'show result')
    if(result['status'] and result['data']):
        conn = pymysql.connect(host="localhost", user="root", password="DxPass@word!@#",
                               database="autolabel",
                               charset="utf8", cursorclass=pymysql.cursors.DictCursor)

        cursor = conn.cursor()
        # 定义要执行的SQL语句
        sql = 'select * from user where id=%s'
        cursor.execute(sql, result['data'])
        user = cursor.fetchone()
        # 关闭光标对象
        cursor.close()
        # 关闭数据库连接
        conn.close()
        returnUser = {
            'id': user["id"],
            'username': user["username"],
            'login_time': user["logintime"],
            'roles': ['admin'],
            'introduction': 'I am a super administrator',
            'avatar': 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            'name': 'Super Admin'
        }
        result = common.trueReturn(returnUser, "请求成功")
    # if (result['status'] and result['data']):
    #     # user = Users.get(Users, result['data'])
    #     # returnUser = {
    #     #     'id': user.id,
    #     #     'username': user.username,
    #     #     'email': user.email,
    #     #     'login_time': user.login_time
    #     # }
    #     result = common.trueReturn(returnUser, "请求成功")
    return jsonify(result)

if __name__ == '__main__':
    app.run()
